import os, socket, time, random

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 7531))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.listen(100)

children = {}
for kid in '1234abcd':
    pid = os.fork()
    if pid:
        children[pid] = kid
    else:
        pid = None
        break  # stop forking

if pid:
    print '[master] running'
    while children:
        pid, status = os.waitpid(0, 0)
        print '[master]', children[pid], 'finished'
        del children[pid]
else:
    print '[worker]', kid, 'started'
    while True:
        conn, addr = sock.accept()
        conn.recv(1024)
#        print '[worker]', kid, addr, conn.recv(1024).split('\r\n')[:1]
#        time.sleep(random.randrange(10, 80) / 10.)
        conn.send('HTTP/1.0 200 OK\r\nServer: test/prefork\r\n\r\n*hello fron %s!*\r\n' % kid)
        conn.close()
